package com.own.component.common.util.executor;

import lombok.NonNull;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.*;

/**
 * ExecutorUtil
 *
 * @author chenxueli
 * @date 2023-10-08 09:19:02
 */
@Component
public final class ExecutorUtil {

    /**
     * 虚拟线程池
     */
    public static final ExecutorService VIRTUAL_THREAD_PER_TASK_EXECUTOR = Executors.newVirtualThreadPerTaskExecutor();

    @Resource
    private ThreadPoolTaskExecutor customAsyncExecutor;

    /**
     * 获取任务执行结果
     *
     * @param future 任务
     * @param <T>    任务执行结果类型
     * @return 任务执行结果
     */
    public static <T> T get(Future<T> future) {
        try {
            return future.get();
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 创建虚拟线程
     *
     * @return 虚拟线程
     */
    public static ExecutorService newVirtualThreadPerTaskExecutor() {
        return Executors.newVirtualThreadPerTaskExecutor();
    }

    /**
     * 新建线程并运行
     *
     * @param runnable 执行内容
     */
    public void execute(@NonNull Runnable runnable) {
        execute(true, runnable);
    }

    /**
     * 新建线程并运行
     *
     * @param condition 判别式
     * @param runnable  执行内容
     */
    public void execute(boolean condition, @NonNull Runnable runnable) {
        if (!condition) {
            return;
        }
        customAsyncExecutor.execute(runnable);
    }

    /**
     * 提交任务
     *
     * @param task 任务
     * @param <T>  任务执行结果类型
     * @return 任务执行结果
     */
    public <T> Future<T> submit(Callable<T> task) {
        return customAsyncExecutor.submit(task);
    }

}
